package com.sogoodsoft.service.common;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.sogoodsoft.entity.app.SysClass;
import com.sogoodsoft.entity.crm.Sms;
import com.sogoodsoft.entity.crm.Smstask;
import com.sogoodsoft.service.app.SysClassService;
import com.sogoodsoft.service.crm.SmsService;
import com.sogoodsoft.service.crm.SmstaskService;

/**
 * <p>执行短信发送任务类</p>
 * <p>定时检查短信列表，如有到时间，且未发送的短信，则发送</p>
 * 被Spring的Quartz MethodInvokingJobDetailFactoryBean定时执行的普通Spring Bean.
 */
public class SMSJob {

	private static Logger logger = LoggerFactory.getLogger(SMSJob.class);
	
	//每次发送后，下一条等待多久才发 单位毫秒
	@SuppressWarnings("unused")
    private static int interval = 500;
	private List<Sms> list;
	private SysClass status;
	private boolean success = false;
	
	@Autowired	
	private SmstaskService taskService;
	@Autowired	
	private SmsService smsService;	
	@Autowired	
	private SysClassService sysService;	
	@Autowired	
	private CommunicateService commService;
	/**
	 * 检查未发短信列表，按时发短信.
	 */

	@SuppressWarnings("static-access")
    public void execute() {
		while(!taskService.isStatus()){
			//状态不允许时，卡这里等着
		}
		list = smsService.getSmsList();
		
		logger.debug("本时间间隔需发短信"+list.size()+"条");
		for(Sms sms:list){
			
			success = commService.sendSMS(sms.getMsg(), sms.getTarget());
			if(success){
				status = sysService.getByCode(Smstask.SEND_STATUS_CODE.SUCCESS.getCODE());
				logger.debug("成功发送短信到手机："+sms.getTarget());
			}else{
				status = sysService.getByCode(Smstask.SEND_STATUS_CODE.FAIL.getCODE());
				logger.debug("短信发送失败，手机："+sms.getTarget());
			}
			//每条短信的发送间隔
//			try {
//				Thread.sleep(interval+10);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			
			sms.setSendSatus(status);
			sms.setSendtime(new Date());
			smsService.save(sms);
			
			//修改任务状态
			Smstask task = sms.getTask();
			taskService.finishTask(task);
			
		}
		logger.debug("本时间间隔共发短信"+list.size()+"条");

	}
}
